package cn.gx.learn.security_boot_jwt_websocket.springsecurity.interceptor;

import cn.gx.learn.security_boot_jwt_websocket.springsecurity.JWT.JWTUtils;
import cn.gx.learn.security_boot_jwt_websocket.base.dal.database.User;
import cn.gx.learn.security_boot_jwt_websocket.springsecurity.dal.UserDetail;
import com.nimbusds.jose.JOSEException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.text.ParseException;

@Component
public class JWTInterceptor extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if(uri.equals("/login")||uri.equals("/register")||uri.equals("/logout")||uri.startsWith("/ws")){
            filterChain.doFilter(request,response);
            return;
        }
        String token =request.getHeader("Authorization");
        if(token==null||token.isEmpty()){
            throw new RuntimeException("JWT header is empty");
        }
        try {
            User user= JWTUtils.paserToken(token);
            UserDetail  userDetail=new UserDetail(user);
            UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(
                    userDetail,
                    null,
                    userDetail.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request,response);
        } catch (ParseException | JOSEException e) {
            throw new RuntimeException(e);
        }


    }
}
